package controllers

import config.{Global, MyFile, MyRow}
import dao.PublicationsDao
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}

import java.io.File
import javax.inject.Inject
import scala.concurrent.ExecutionContext

class PublicationsController @Inject()(publicationsDao: PublicationsDao, cc: ControllerComponents)
                                      (implicit exec: ExecutionContext) extends AbstractController(cc) with MyRow with MyFile{

  def publictionsPage = Action { implicit request =>
    Ok(views.html.publications.publictionsPage())
  }

  def getAllPublications = Action.async {implicit request=>
    publicationsDao.getAll.map{x=>
      Ok(Json.toJson(x.map(_.getMapByT())))
    }
  }

  def downloadPdf(file: String) = Action { implicit request =>
    val files = s"${Global.path}/publications/".listFile.filter(_.getName.startsWith(file +"-")).head
    val filename = new String(("attachment;filename=\"" + files.getName + "\"").getBytes("GBK"), "ISO_8859_1")
    Ok.sendFile(files).withHeaders(
      //缓存
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> filename,
      CONTENT_TYPE -> "application/x-download"
    )
  }

  def openPdf(file: String) = Action { implicit request =>
    val files = s"${Global.path}/publications/".listFile.filter(_.getName.startsWith(file +"-")).head
    val filename = new String(("filename=\"" + files.getName + "\"").getBytes("GBK"), "ISO-8859-1")
    Ok.sendFile(files).withHeaders(
      //缓存
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> filename,
      CONTENT_TYPE -> "text/plain"
    )
  }


}
